import fs from 'fs';
import { _ } from 'meteor/underscore';
import { Random } from 'meteor/random';
import { Collections } from '/imports/files/fileCollections';
import { cosConf, cos } from './cos';
import { Channels } from '/imports/models/Channels';

const bound = Meteor.bindEnvironment((callback) => {
  return callback();
});

/**
 * 修改原记录文件地址
 * @param {String} type 上传文件类型
 * @param {String} ownerId 原记录的_id
 * @param {String} link 新的文件地址
 */
const updateFileLink = function (type, ownerId, link) {
  if (typeof type === 'string' && typeof ownerId === 'string' && typeof link === 'string') {
    switch (type) {
      case 'user-profile-avatar':
        const upd = { $set: {} };
        upd['$set']['profile.avatar'] = link;
        Meteor.users.update({
          _id: ownerId
        }, upd);
        break;
      case 'channel-cover':
        const upd1 = { $set: {} };
        upd1['$set']['cover'] = link;
        Channels.update({
          _id: ownerId
        }, upd1);
        break;
      default:
        return;
    }
  }
};

Collections.Images = new FilesCollection({
  collectionName: 'Images',
  allowClientCode: true,
  onAfterUpload(fileRef) {
    _.each(fileRef.versions, (vRef, version) => {
      const filePath = fileRef.meta.location + (Random.id()) + '-' + version + fileRef.extensionWithDot;
      cos.putObject({
        Bucket: cosConf.Bucket,
        Region: cosConf.Region,
        Key: filePath,
        Body: fs.createReadStream(vRef.path),
        ContentLength: fs.statSync(vRef.path).size
      }, (error, result) => {
        bound(() => {
          if (error) {
            console.error(error);
          } else {
            updateFileLink(fileRef.meta.type, fileRef.meta.ownerId, result.Location);

            const upd = { $set: {} };
            upd['$set']['versions.' + version + '.meta.pipePath'] = filePath;

            this.collection.update({
              _id: fileRef._id
            }, upd, (updError) => {
              if (updError) {
                console.error(updError);
              } else {
                this.unlink(this.collection.findOne(fileRef._id), version);
              }
            });
          }
        });
      });
    });
  }
});

Houston.hide_collection(Collections.Images.collection);
Houston.hide_collection(Collections.Images._preCollection);